import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { InfiniteScroll, List, FloatingBubble, Toast } from "antd-mobile";
import { ScanningOutline } from "antd-mobile-icons";
import { SearchBox, OrderCardTitle, BottomBtn } from "@components";
import { createAction } from "@common/utils";
import {
  PUSH_PAGE_STACK,
  SET_PAGE_TITLE,
} from "@store/global-state/action-types";
import { SAGA_PROD_INBOUND_PUSH_2_SERVER } from "@store/prod-inbound/saga-types";
import {
  SET_PROD_INBOUND_CURRENT_ORDER,
  SET_PROD_INBOUND_ORDER_LIST,
} from "@store/prod-inbound/action-types";
import { loadProdInboundSourceOrderList } from "@store/prod-inbound/async-call";

const ProdInbound = () => {
  const [searchTxt, setSearchTxt] = useState(null);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [hasMore, setHasMore] = useState(false);
  const orderList = useSelector((state) => state.prodInbound.orderList);
  const orderListOffset = useSelector(
    (state) => state.prodInbound.orderListOffset
  );

  const loadList = async ({ offset }) => {
    let payload = {
      searchTxt: searchTxt ? searchTxt : null,
      offset: /^\d+$/.test(offset) ? offset : orderListOffset,
      maxResult: 5,
      callback: (resp) => setHasMore(resp.payload.items.length >= 5),
    };
    await loadProdInboundSourceOrderList(payload);
  };

  useEffect(() => {
    dispatch(createAction(SET_PAGE_TITLE, "成品入库"));
    loadList({ offset: 0 });
    return () => {
      dispatch(
        createAction(SET_PROD_INBOUND_ORDER_LIST, { items: [], offset: 0 })
      );
    };
  }, []);

  const loadMore = async () => {
    await loadList({});
  };

  const Descriptions = ({ record }) => (
    <>
      <p>单据类型: {record.erpOrderType}</p>
      <p>单据日期: {record.createdAt}</p>
      <p>经办人: {record.operators}</p>
      {record.errMsg ? (
        <p style={{ color: "red" }}>失败原因: {record.errMsg}</p>
      ) : null}
    </>
  );

  const openOrder = ({ id, orderNum }) => {
    dispatch(createAction(SET_PROD_INBOUND_CURRENT_ORDER, { id, orderNum }));
    let path = `/app/prod-inbound/order-lines?id=${id}`;
    navigate(path);
    dispatch(createAction(PUSH_PAGE_STACK, path));
  };

  const openScanDirectlyPage = () => {
    let path = `/app/prod-inbound/scan-directly`;
    navigate(path);
    dispatch(createAction(PUSH_PAGE_STACK, path));
  };

  const handlePush = () => {
    dispatch(
      createAction(SAGA_PROD_INBOUND_PUSH_2_SERVER, {
        isMix: false,
        callback: () =>
          Toast.show({
            icon: "success",
            content: "推送完毕",
            maskClickable: false,
          }),
      })
    );
  };

  const handleSearch = () => {
    loadList({ offset: 0 });
  };

  return (
    <>
      <SearchBox
        placeholder="请输入单号"
        searchHandler={handleSearch}
        setSearchTxtHandler={setSearchTxt}
      />
      <div style={{ marginTop: "102px", marginBottom: "65px" }}>
        <List>
          {orderList.map((record, idx) => (
            <List.Item
              key={idx}
              style={{ backgroundColor: idx % 2 === 0 ? "#EBF2FD" : "#FFFAF1" }}
              description={<Descriptions record={record} />}
              onClick={() => openOrder(record)}
            >
              <OrderCardTitle
                title={`单号: ${record.orderNum}`}
                status={record.status}
              />
            </List.Item>
          ))}
        </List>
        <InfiniteScroll
          style={{ backgroundColor: "#F5F5F5" }}
          loadMore={loadMore}
          hasMore={hasMore}
          threshold="10"
        />
      </div>
      <BottomBtn
        items={[{ btnTxt: "推送", color: "primary", handler: handlePush }]}
      />
      <FloatingBubble
        style={{
          "--initial-position-bottom": "78px",
          "--initial-position-right": "18px",
          "--edge-distance": "24px",
        }}
        onClick={openScanDirectlyPage}
      >
        <ScanningOutline fontSize={32} />
      </FloatingBubble>
    </>
  );
};

export default ProdInbound;
